const express = require("express");

const db = require("../modules/DBhelper");

const moment = require("moment");

//创建路由
let router = express.Router();
router.post("/login", async function (request, response, next) {
  let userObj = request.body;
  let sql = "SELECT*FROM `userinfo` WHERE `u_phone` = ? AND `u_pwd` =? ;"
  let params = [
    userObj.user,
    userObj.upwd
  ];
  let result = await db.exec(sql, params);
  let isLogin = result && result.length >= 1;
  if (isLogin) {
    delete (result[0].u_pwd);// 是u_pwd,这个字段来自于数据库
  }
  let messages = {
    msg: isLogin ? "登录成功" : "登录失败",
    data: isLogin ? result : '',
    status: isLogin ? 200 : -200
  }
  response.json(messages);
})


router.get("/checkname", async (request, response, next) => {
  try {
    let sql = "SELECT*FROM `userinfo` WHERE `u_name`=? ;";
    let result = await db.exec(sql, [request.query.uname]);
    let isCheckeName = !(result && result.length >= 1);

    response.end(isCheckeName + "");
  } catch (error) {
    response.end("false")
  }
})

router.post("/reg", async function (request, response, next) {
  let userObj = request.body;

  let sql = "INSERT INTO `userinfo`(`u_phone`,`u_pwd`,`u_name`)VALUE(?,?,?)"
  let params = [
    userObj.user,
    userObj.upwd,
    userObj.uname
  ];
  let result = await db.exec(sql, params);
  let isReg = result && result.affectedRows >= 1;

  let messages = {
    msg: isReg ? "注册成功" : "注册失败",
    status: isReg ? 200 : -200
  }
  response.json(messages);
})

module.exports = {router}